import Vue from 'vue'
import VueRouter from 'vue-router'
//导入前置路由地址数组
import Arrrouter from '@/router/router.js'

import Login from '@/components/MyLogin.vue'

import Home from '@/components/MyHome.vue'

import Users from '@/components/menus/MyUsers.vue'
import Rights from '@/components/menus/MyRights.vue'
import Goods from '@/components/menus/MyGoods.vue'
import Orders from '@/components/menus/MyOrders.vue'
import Setting from '@/components/menus/MySettings.vue'
import UserDetail from '@/components/user/MyUserDetail.vue'
import AddUser from '@/components/user/addUser.vue'
import AbsentList from '@/components/menus/MyAbsent.vue'
import SignInout from '@/components/menus/MySigninout.vue'
import Reduse from '@/components/menus/MyReduse.vue'
import Approval from '@/components/menus/MyApproval.vue'
import Dashboard from '@/components/menus/Dashboard.vue'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    //路由重定向
    { path: '/', redirect: '/login' },
    //登录路由规则
    { path: '/login', component: Login },
    {
      path: '/home',
      component: Home,
      //路由重定向
      redirect: '/home/Dashboard',
      children: [
        //路由重定向
        //子路由规则
        { path: 'users', component: Users , meta:{
          roles:[2]
        }},
        { path: 'rights', component: Rights, meta:{
          roles:[0, 1, 2, 3]
        } },
        { path: 'goods', component: Goods, meta:{
          roles:[2]
        } },
        // { path: 'orders', component: Orders },
        // { path: 'setting', component: Setting },
        { path: 'absentlist', component: AbsentList , meta:{
          roles:[0,1,2,3]
        }},
        { path: 'signinout', component: SignInout, meta:{
          roles:[0,1,2,3]
        } },
        { path: 'reduse', component: Reduse, meta:{
          roles:[0,1,2,3]
        } },
        { path: 'approval', component: Approval, meta:{
          roles:[1,3]
        } },
        { path: 'userinfo/:id', component: UserDetail, props: true , meta:{
          roles:[2]
        }},
        { path: 'addUser', component: AddUser , meta:{
          roles:[2]
        }},
        { path: 'Dashboard', component: Dashboard , meta:{
        }}
      ]
    },
  ]
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  if (Arrrouter.indexOf(to.path) != -1) {
    const token = localStorage.getItem('token')
    const role = Number(localStorage.getItem('job'))
    const roles = to.meta.roles
    console.log(role)
    console.log(roles)
    if(roles) console.log(roles.includes(role))
    if (token) {
      next()
    } else {
      next('/login')
    }
    if(roles && roles.indexOf(role) === -1){
      alert("您无权访问")
      next('/home')
    }
  } else {
    next()
  }
})

export default router